from robyn import SubRouter
from services import user_service
from constants import HttpStatus, DefaultValues, Role
from middleware.auth_middleware import auth_required
from utils.validation_util import Validator, create_validation_response
from utils.error_handler import unified_response, get_error_response, handle_database_error
import traceback

user_controller = SubRouter(__file__, prefix="/api/users")

@user_controller.post("/register")
async def register_user(request):
    """用户注册接口 - 完整的参数验证示例"""
    try:
        # 获取JSON数据
        data = request.json()
        
        # 使用验证工具进行参数验证
        validator = Validator()
        
        # 验证用户名
        validator.required("username", data.get("username"))
        validator.string("username", data.get("username"), min_length=3, max_length=20)
        validator.regex("username", data.get("username"), r"^[a-zA-Z0-9_]+$", "用户名只能包含字母、数字和下划线")
        
        # 验证密码
        validator.required("password", data.get("password"))
        validator.string("password", data.get("password"), min_length=6, max_length=50)
        
        # 验证邮箱
        if data.get("email"):
            validator.required("email", data.get("email"))
            validator.email("email", data.get("email"))
            validator.string("email", data.get("email"), max_length=100)
        
        # 验证手机号（可选）
        if data.get("phone"):
            validator.regex("phone", data.get("phone"), r"^1[3-9]\d{9}$", "手机号格式不正确")
        
        # 验证年龄（可选）
        if data.get("age") is not None:
            validator.integer("age", data.get("age"), min_value=1, max_value=120)
        
        # 验证性别（可选）
        if data.get("gender"):
            validator.one_of("gender", data.get("gender"), ["male", "female", "other"])
        
        # 如果有验证错误，返回400状态码和详细错误信息
        if validator.has_errors():
            return create_validation_response(validator.get_errors(), data)
        
        # 参数验证通过，继续处理业务逻辑
        new_user = user_service.createUser(data)
        if new_user is None:
            return unified_response(HttpStatus.INTERNAL_SERVER_ERROR, "User registration failed", None)
        
        return unified_response(HttpStatus.OK, "用户注册成功", new_user)
        
    except Exception as e:
        return unified_response(HttpStatus.INTERNAL_SERVER_ERROR, "用户注册失败", None, error=e)

@user_controller.get("/")
@auth_required()
async def getUsers(request):
    """
    获取用户列表（支持分页）
    """
    try:
        skip = int(request.query_params.get("skip", DefaultValues.SKIP))
        limit = int(request.query_params.get("limit", DefaultValues.LIMIT))
        
        users = user_service.getUsers(skip=skip, limit=limit)
        
        return unified_response(HttpStatus.OK, "Users retrieved successfully", users)
    
    except Exception as e:
        return unified_response(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to retrieve users", None, error=e)

@user_controller.get("/:user_id")
@auth_required()
async def getUser(request):
    """
    根据ID获取单个用户
    """
    try:
        user_id = request.path_params.get("user_id")
        
        user_model = user_service.getUser(user_id)
        
        if user_model is None:
            return unified_response(HttpStatus.NOT_FOUND, "User not found", None)
        
        return unified_response(HttpStatus.OK, "User retrieved successfully", user_model)
    
    except Exception as e:
        return unified_response(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to retrieve user", None, error=e)

@user_controller.put("/:user_id")
@auth_required()
async def update_user(request):
    """更新用户信息 - 路径参数和JSON数据验证"""
    try:
        # 获取路径参数
        user_id = request.path_params.get("user_id")
        
        # 获取JSON数据
        data = request.json()
        
        # 使用验证工具进行参数验证
        validator = Validator()
        
        # 验证邮箱（可选）
        if data.get("email"):
            validator.email("email", data.get("email"))
            validator.string("email", data.get("email"), max_length=100)
        
        # 验证手机号（可选）
        if data.get("phone"):
            validator.regex("phone", data.get("phone"), r"^1[3-9]\d{9}$", "手机号格式不正确")
        
        # 验证年龄（可选）
        if data.get("age") is not None:
            validator.integer("age", data.get("age"), min_value=1, max_value=120)
        
        # 验证性别（可选）
        if data.get("gender"):
            validator.one_of("gender", data.get("gender"), ["male", "female", "other"])
        
        # 验证个人简介（可选）
        if data.get("bio"):
            validator.string("bio", data.get("bio"), max_length=500)
        
        # 如果有验证错误，返回400状态码和详细错误信息
        if validator.has_errors():
            return create_validation_response(validator.get_errors(), data)
        
        # 参数验证通过，继续处理业务逻辑
        updated_user = user_service.updateUser(user_id, data)
        if updated_user is None:
            return unified_response(HttpStatus.NOT_FOUND, "User not found", None)
        
        return unified_response(HttpStatus.OK, "用户信息更新成功", updated_user)
        
    except Exception as e:
        return unified_response(HttpStatus.INTERNAL_SERVER_ERROR, "更新用户信息失败", None, error=e)

@user_controller.delete("/:user_id")
@auth_required()
async def deleteUser(request):
    """
    删除用户
    """
    try:
        user_id = request.path_params.get("user_id")
        
        is_deleted = user_service.deleteUser(user_id)
        
        if not is_deleted:
            return unified_response(HttpStatus.NOT_FOUND, "User not found", None)
        
        return unified_response(HttpStatus.OK, "User deleted successfully", None)
    
    except Exception as e:
        return unified_response(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to delete user", None, error=e)

@user_controller.get("/search")
@auth_required()
async def search_users(request):
    """搜索用户 - 查询参数验证"""
    try:
        # 获取查询参数
        query_params = request.query_params
        
        # 使用验证工具进行参数验证
        validator = Validator()
        
        # 验证关键词
        if query_params.get("keyword"):
            validator.string("keyword", query_params.get("keyword"), max_length=50)
        
        # 验证页码
        page = int(query_params.get("page", DefaultValues.SKIP)) # Use DefaultValues.SKIP for page
        limit = int(query_params.get("limit", DefaultValues.LIMIT))
        validator.integer("page", page, min_value=0) # page can be 0 for skip
        validator.integer("limit", limit, min_value=1, max_value=100)
        
        # 验证排序字段
        sort_by = query_params.get("sort_by", "username")
        validator.one_of("sort_by", sort_by, ["username", "email", "created_time"])
        
        # 验证排序方式
        sort_order = query_params.get("sort_order", "asc")
        validator.one_of("sort_order", sort_order, ["asc", "desc"])
        
        # 验证状态
        if query_params.get("status"):
            validator.one_of("status", query_params.get("status"), ["active", "inactive"]) # Assuming 'is_active' maps to 'active'/'inactive'
        
        # 如果有验证错误，返回400状态码和详细错误信息
        if validator.has_errors():
            return create_validation_response(validator.get_errors(), dict(query_params))
        
        # 参数验证通过，继续处理业务逻辑
        users = user_service.searchUsers(
            keyword=query_params.get("keyword"),
            skip=page, # Use page as skip
            limit=limit,
            sort_by=sort_by,
            sort_order=sort_order,
            status=query_params.get("status")
        )
        
        return unified_response(
            HttpStatus.OK,
            "搜索用户成功",
            {
                "search_params": {
                    "keyword": query_params.get("keyword"),
                    "page": page,
                    "limit": limit,
                    "sort_by": sort_by,
                    "sort_order": sort_order,
                    "status": query_params.get("status")
                },
                "users": users
            }
        )
        
    except Exception as e:
        return unified_response(HttpStatus.INTERNAL_SERVER_ERROR, "搜索用户失败", None, error=e)


@user_controller.get("/info")
async def info(request):
        try:
            return {
                "code": HttpStatus.OK,
                "msg": "获取成功",
                "data": {
                    "userId": "1",
                    "username": "admin",
                    "realName": "超级管理员",
                    "avatar": "avatar.png",
                    "homePath": "/analytics",
                    "description": "一位超级管理员",
                    "roles": [
                        {
                            "roleName": "Super Admin",
                            "value": "super"
                        }
                    ]
                }
            }

        except Exception as e:
            # 在调试模式下返回详细的错误信息，包括基本错误信息
            error_response = handle_database_error(e, "codes")
            # 确保基本错误信息始终可见
            if "error_info" not in error_response:
                error_response["error_info"] = {
                    "error_type": type(e).__name__,
                    "error_message": str(e)
                }
            return error_response